import { createRouter, createWebHistory } from "vue-router";
import request from "../api/request";
import { ElMessage } from 'element-plus'

export const routes = [
    { path: "/", redirect: "/login" },
    {
        path: "/login",
        name: "login",
        component: () => import("../views/login.vue"),
    },
    {
        path: "/userMain",
        name: "userMain",
        component: () => import("../views/userMain.vue"),
    },
    {
        path: "/userInfo",
        name: "userInfo",
        component: () => import("../views/userInfo.vue"),
    },
    {
        path: "/borrowingSystem",
        name: "borrowingSystem",
        component: () => import("../views/borrowingSystem.vue"),
    },
    {
        path: "/booksManage",
        name: "booksManage",
        component: () => import("../views/booksManage.vue"),
    },
    {
        path: "/borrowedBooks",
        name: "borrowedBooks",
        component: () => import("../views/borrowedBooks.vue"),
    },
    {
        path: "/userManage",
        name: "userManage",
        component: () => import("../views/userManage.vue"),
    },
];

const router = createRouter({
    routes,
    history: createWebHistory(),
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
    if (to.path != ("/login" || "register")) {
        request.get("/check").then((res) => {
            if (res.status == 0) {
                return next();
            }
        }).catch((err)=>{
            ElMessage({
                type:'warning',
                message:'身份信息失效，请重新登录'
            })
            return next('/login');
        })
    } else {
        next();
    }
});

export default router;
